package com.ylxin.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author 29048
 * @version V1.0
 * @Project mybatis
 * @Package com.ylxin.mybatis.utils
 * @Description: 公共类  工具类
 * Create by 杨立新 @Date 2022/8/25 20:43
 */
public class MyBatisUtils {

    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接,此方法是被动调用的。当获取mapper对象的时候如果没有则调用此方法
     * @return
     */
    public static SqlSession openSession() {
        //创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建sqlSession后及时保存到threadLocal
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    /**
     * 提交事务
     */
    public static void commit(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.commit();
        }
    }

    /**
     * 回滚事务
     */
    public static void rollback(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
        }
    }

    /**
     * 关闭连接
     */
    public static void close(){
        SqlSession sqlSession = threadLocal.get();
        sqlSession.close();
        //移除，防止内存泄露
        threadLocal.remove();
    }

    /**
     * 获取Mapper对象
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static  <T> T  getMapper(Class<T> clazz) {
        SqlSession sqlSession = threadLocal.get();
        //如果没有sqlSession的情况下创建
        if(sqlSession == null){
            //创建一个，创建sqlSession后已经保存了
            sqlSession = openSession();
//            threadLocal.set(sqlSession);
        }
        //返回mapper
        return sqlSession.getMapper(clazz);
    }
}
